from flask import request, jsonify, current_app
from flask_jwt_extended import jwt_required
from ..services import IntersectionService
from ..utils import success_response, error_response, validate_json_data
from ..models import Intersection
from . import api

@api.route('/intersections', methods=['GET'])
@jwt_required()
def get_intersections():
    """获取路口数据列表"""
    try:
        page = int(request.args.get('page', 1))
        per_page = int(request.args.get('limit', 10))
        keyword = request.args.get('keyword', '')
        start_date = request.args.get('start_date')
        end_date = request.args.get('end_date')
        
        result = IntersectionService.get_intersections(
            page=page, 
            per_page=per_page, 
            keyword=keyword,
            start_date=start_date,
            end_date=end_date
        )
        
        return success_response(result, '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取路口数据列表错误: {str(e)}')
        return error_response('获取路口数据列表失败', 500)

@api.route('/intersections', methods=['POST'])
@jwt_required()
def create_intersection():
    """创建路口数据"""
    try:
        data = request.get_json()
        
        # 验证数据
        required_fields = ['name', 'type', 'location']
        for field in required_fields:
            if not data.get(field):
                return error_response(f'缺少必要字段: {field}', 400)
        
        intersection = IntersectionService.create_intersection(data)
        return success_response(intersection.to_dict(), '创建成功', 201)
    except Exception as e:
        current_app.logger.error(f'创建路口数据错误: {str(e)}')
        return error_response('创建路口数据失败', 500)

@api.route('/intersections/<int:intersection_id>', methods=['GET'])
@jwt_required()
def get_intersection(intersection_id):
    """根据ID获取路口数据"""
    try:
        intersection = IntersectionService.get_intersection_by_id(intersection_id)
        if not intersection:
            return error_response('路口数据不存在', 404)
        
        return success_response(intersection.to_dict(), '获取成功')
    except Exception as e:
        current_app.logger.error(f'获取路口数据错误: {str(e)}')
        return error_response('获取路口数据失败', 500)

@api.route('/intersections/<int:intersection_id>', methods=['PUT'])
@jwt_required()
def update_intersection(intersection_id):
    """更新路口数据"""
    try:
        intersection = IntersectionService.get_intersection_by_id(intersection_id)
        if not intersection:
            return error_response('路口数据不存在', 404)
        
        data = request.get_json()
        updated_intersection = IntersectionService.update_intersection(intersection_id, data)
        
        return success_response(updated_intersection.to_dict(), '更新成功')
    except Exception as e:
        current_app.logger.error(f'更新路口数据错误: {str(e)}')
        return error_response('更新路口数据失败', 500)

@api.route('/intersections/<int:intersection_id>', methods=['DELETE'])
@jwt_required()
def delete_intersection(intersection_id):
    """删除路口数据"""
    try:
        result = IntersectionService.delete_intersection(intersection_id)
        if not result:
            return error_response('路口数据不存在', 404)
        
        return success_response(None, '删除成功')
    except Exception as e:
        current_app.logger.error(f'删除路口数据错误: {str(e)}')
        return error_response('删除路口数据失败', 500)